package com.mbl.base.modular.mall.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mbl.base.config.enums.ResultEnum;
import com.mbl.base.core.common.controller.BaseController;
import com.mbl.base.core.common.dto.MblResult;
import com.mbl.base.core.common.page.LayuiPageFactory;
import com.mbl.base.core.utils.UtilHttp;
import com.mbl.base.modular.mall.dto.GoodsAllinone;
import com.mbl.base.modular.mall.entity.Goods;
import com.mbl.base.modular.mall.service.IBrandService;
import com.mbl.base.modular.mall.service.ICategoryService;
import com.mbl.base.modular.mall.service.IGoodsService;
import com.mbl.base.modular.mall.vo.CatVo;
import com.qcloud.cos.utils.UrlEncoderUtils;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import jodd.util.URLDecoder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lwj
 * @since 2020-02-27
 */
@RestController
@RequestMapping("/mall/goods")
public class GoodsController extends BaseController<Goods, IGoodsService> {
    @Autowired
    private IBrandService brandService;
    @Autowired
    private ICategoryService categoryService;

    @Override
    public void machiningList(QueryWrapper<Goods> queryWrapper, String condition) {
        final String type = UtilHttp.getPara("type");
        queryWrapper.eq(StringUtils.isNotBlank(type), "type", type);
        final String goodsId = UtilHttp.getPara("goodsId");
        queryWrapper.eq(StringUtils.isNotBlank(goodsId), "id", goodsId);
        final String name = UtilHttp.getPara("name");
        queryWrapper.like(StringUtils.isNotBlank(name), "name", name);
        final String addTimeStr = UtilHttp.getPara("addTimeStr");
        final String addTimeEnd = UtilHttp.getPara("addTimeEnd");
        queryWrapper.between(StringUtils.isNoneBlank(addTimeStr, addTimeEnd), "create_time", addTimeStr, addTimeEnd);
        super.machiningList(queryWrapper, condition);
    }

    /**
     * 商品分类及品牌制造商数据获取
     * @return
     */
    @GetMapping("/catAndBrand")
    public Object catAndBrand(){
        List<CatVo> categoryList = new ArrayList<>();
        // 分类所属数据封装
        categoryService.query().eq("level", "L1").list().forEach(categoryL1 -> {
            CatVo l1CatVo = new CatVo();
            l1CatVo.setValue(categoryL1.getId());
            l1CatVo.setLabel(categoryL1.getName());
            List<CatVo> children = new ArrayList<>();
            categoryService.query().eq("pid", categoryL1.getId()).list().forEach(categoryL2 -> {
                CatVo l2CatVo = new CatVo();
                l2CatVo.setValue(categoryL2.getId());
                l2CatVo.setLabel(categoryL2.getName());
                children.add(l2CatVo);
            });
            l1CatVo.setChildren(children);
            categoryList.add(l1CatVo);
        });
        // 品牌制造商数据封装
        List<Map<String, Object>> brandList = new ArrayList<>();
        brandService.list().forEach(brand -> {
            Map<String, Object> b = new HashMap<>(2);
            b.put("value", brand.getId());
            b.put("label", brand.getName());
            brandList.add(b);
        });
        Map<String, Object> data = new HashMap<>();
        data.put("categoryList", categoryList);
        data.put("brandList", brandList);
        return MblResult.success(data);
    }

    /**
     * 创建商品
     * @param goodsAllinone
     * @return
     */
    @PostMapping("/create")
    public Object create(@RequestBody GoodsAllinone goodsAllinone) {
        if(getService().create(goodsAllinone)){
            return MblResult.success();
        }
        return MblResult.renum(ResultEnum.SERVER_ERR);
    }

    /**
     * 更新商品
     * @param goodsAllinone
     * @return
     */
    @PostMapping("/update")
    public Object update(@RequestBody GoodsAllinone goodsAllinone) {
        if(getService().update(goodsAllinone)){
            return MblResult.success();
        }
        return MblResult.renum(ResultEnum.SERVER_ERR);
    }

    /**
     * 详情
     * @param id
     * @return
     */
    @GetMapping("/view")
    public Object view(Integer id){
        return MblResult.success(getService().detail(id));
    }
    /**
     * 高级查找
     * @return
     */
    @GetMapping("/heList")
    public Object heList(String name, String tags){
        Page page = LayuiPageFactory.defaultPage();//获取分页参数
        QueryWrapper<Goods> queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("update_time");
        queryWrapper.like(StringUtils.isNotBlank(name),"name",name);
        if(StringUtils.isNotBlank(tags)){
            tags =  URLDecoder.decode(tags, "UTF-8");
            JSON.parseArray(tags).forEach(con -> {
                JSONObject obj = (JSONObject) con;
                final String key = obj.getString("key");
                if(StringUtils.startsWith(key,"type_")){
                    queryWrapper.eq("category_id",StringUtils.substringAfter(key, "type_"));
                }
                if(StringUtils.startsWith(key,"status_")){
                    queryWrapper.like("sb_json",key);
                }
            });
        }
        IPage page1 = getService().page(page, queryWrapper);
        return MblResult.success(page1);
    }

    @PostMapping("/listByCategoryId")
    @ApiOperation("根据类别id进行所有子集类别的商品查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "limit", value = "数据条数"),
            @ApiImplicitParam(name = "page", value = "页码"),
            @ApiImplicitParam(name = "id", value = "类别id")
    })
    public MblResult listByCategoryId(@RequestParam Long id, String name){
        List<Long> categoryIds = new ArrayList<>();
        categoryIds.add(id);
        categoryIds.addAll(categoryService.query().eq("pid", id).list().stream().map(category -> category.getId()).collect(Collectors.toList()));
        Page page = LayuiPageFactory.defaultPage();//获取分页参数
        QueryWrapper<Goods> queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("update_time");
        if(StringUtils.isNotBlank(name)){
            queryWrapper.like("name", name);
        }
        queryWrapper.in("category_id", categoryIds);
        IPage page1 = getService().page(page, queryWrapper);
        return MblResult.success(page1);
    }
}

